import random

from flask import Blueprint, render_template, session, jsonify

from config import db
from models.models import User, History, Goods
from sqlalchemy import func

index_service = Blueprint('index_service', __name__)


@index_service.route("/")
def index():
    return render_template('index.html')


@index_service.route("/api/username")
def api_username():
    user_id = session.get("user_id")
    user = User.query.filter_by(id=user_id).first()
    data = {
        "username": user.name
    }
    return jsonify(data)


@index_service.route("/recomment")
def recomment():
    type_counts = db.session.query(History.type, func.count(History.type)).group_by(History.type).all()
    if not type_counts:
        recommended_goods = random.sample(Goods.query.all(), 8)
    else:
        total = sum(count for _, count in type_counts)

        recommendations_per_type = {}

        for type_, count in type_counts:
            recommendations_per_type[type_] = (count, int(count / total * 12))

        recommended_goods = []
        for type_, (_, recommend_count) in recommendations_per_type.items():
            goods_of_type = Goods.query.filter_by(type=type_).all()
            recommended_goods.extend(random.sample(goods_of_type, min(recommend_count, len(goods_of_type))))

        recommended_goods.sort(key=lambda x: -recommendations_per_type[x.type][0])

    recommendations_data = []
    for recommended_good in recommended_goods:
        recommendation = {
            'id': recommended_good.id,
            'name': recommended_good.name,
            'type': recommended_good.type,
            'price': recommended_good.price,
            'outline': recommended_good.outline,
            'img_url': recommended_good.img_url,
            'link_url': recommended_good.link_url
        }
        recommendations_data.append(recommendation)

    return jsonify({'data': recommendations_data})
